/**
 * 用户权限校验
 */

'use strict';

var Promise = require('bluebird');
var UserModel = require('../models/user');
var _ = require('lodash');

var global = require('../global');
var Utils = require('../helper/utils');

const UserFields = '_id user_email user_nickname user_status user_role user_registered';
const UserFieldsArray = UserFields.split(' ');

module.exports = {

  /**
   * 获取用户列表
   *
   */
  getList: function(page){
    return new Promise(function(resolve, reject){
      /**
       * page,pageSize,conditions,fields,populate,sort,callback
       */
      UserModel.pageQuery(page, global.pageSize, {}, {user_password:0,__v:0} , '',{user_registered:'asc'},function(err, doc){
        if ( err ) {reject('查询数据库错误')}
        resolve(doc);
      });
    })
  },

  /**
   * 添加用户
   * @param options
   */
  add: function (options) {

    return new Promise(function(resolve, reject){
      UserModel.findOne({user_email: options.user_email}, (err, doc) => {
        if ( err ) {reject(err);}
        if(!doc){
          options.user_password = Utils.md5(options.user_password+global.salt);
          UserModel.insertOne(options, (err,doc) => {
            if ( err ) {reject(err);}
            var res = _.pick(doc,UserFieldsArray);
            resolve(res);
          });
        }else{
          reject('用户已经存在');
        }
      });
    });

  },
  
  /**
   * 用户信息存入，并将信息返回
   */
  updateInfo: function(options) {
    const _id = options._id;
    return new Promise(function (resolve, reject) {
      UserModel.findAndUpdate({_id:_id}, options, function (err, doc) {
        if(err){ reject(err) }
        if(doc == null) { reject('没有找到该ID') }
        var res = _.pick(doc,UserFieldsArray);
        resolve(res);
      })
    })
  },

  /**
   * 删除用户
   * @param _id
   */
  remove: function(_id){
    return new Promise(function (resolve, reject) {
      UserModel.findAndRemove({_id:_id},function (err, doc) {
        if(err){ reject('数据库错误') }
        if(doc == null) { reject('没有找到该ID') }
        resolve(doc);
      })
    })
  }

}